<!--  -->
<template>
    <div>


        <!-- 正文 -->
        <div style="padding-bottom: 42px;">
            <van-form @submit="sureButtonClick" @failed="failedMethod">

                <!-- 头部 -->
                <div class="font15 mt10">
                    <div class="pl10">
                        <span class="titletext ">项目变更.新增里程碑</span>
                    </div>

                    <div class="redtext mt10 mb5 font13 pl10">
                        <span>提示：该表单带*字段都为必填项</span>
                    </div>

                    <div class="bcolor-e" style="height: 2px;"></div>
                </div>

                <div>

                    <van-field readonly :right-icon="formEditable ? 'arrow' : ''" name="contractArrangePayTime"
                        v-model="mFromdata.contractArrangePayTime" label="合同约定交付时间:" label-width="9em"
                        @click="showContractArrangePayTimePopupView = formEditable" />
                    <van-popup v-model="showContractArrangePayTimePopupView" position="bottom" get-container="body">
                        <van-datetime-picker v-model="currentContractArrangePayTime" :formatter="formatter" type="date"
                            @confirm="contractArrangePayTimeOnComfirm"
                            @cancel="showContractArrangePayTimePopupView = false" />
                    </van-popup>

                    <van-field readonly required name="planEndDate" v-model="mFromdata.planEndDate" label="里程碑计划完成时间:"
                        label-width="10em" :right-icon="formEditable ? 'arrow' : ''"
                        @click="showPlanEndDatePopupView = formEditable"
                        :rules="[{ required: formEditable, message: '请填写里程碑计划完成时间' }]" />
                    <van-popup v-model="showPlanEndDatePopupView" position="bottom" get-container="body">
                        <van-datetime-picker v-model="currentPlanEndDate" :formatter="formatter" type="date"
                            @confirm="planEndDateOnComfirm" @cancel="showPlanEndDatePopupView = false" />
                    </van-popup>


                    <van-field readonly required name="milestoneNode" v-model="mFromdata.milestoneNode" label="里程碑节点:"
                        label-width="6em" :right-icon="formEditable ? 'arrow' : ''" @click="milestoneNodeClick()"
                        :rules="[{ required: formEditable, message: '请选择里程碑节点' }]" />
                    <van-popup v-model="milestoneNodeShowPopop" position="bottom" get-container="body">
                        <van-picker show-toolbar value-key="name" :columns="milestoneNodeColumns"
                            @confirm="milestoneNodeClickConfirm" @cancel="milestoneNodeShowPopop = false">
                        </van-picker>
                    </van-popup>


                    <van-field :readonly='!formEditable' required name="milestoneDescription"
                        v-model="mFromdata.milestoneDescription" label="里程碑描述:" label-width="6em"
                        :rules="[{ required: formEditable, message: '请填写里程碑描述' }]" />
                    <van-field :readonly='!formEditable' required name="planPersonName"
                        v-model="mFromdata.planPersonName" label="计划交付人姓名:" label-width="8em"
                        :rules="[{ required: formEditable, message: '请填写计划交付人姓名' }]" />
                    <van-field :readonly='!formEditable' required name="planPersonOA" v-model="mFromdata.planPersonOA"
                        label="计划交付人OA:" label-width="8em"
                        :rules="[{ required: formEditable, message: '请填写计划交付人OA' }]" />

                    <div>
                        <van-field label-width="7em" readonly label="分解证明资料:">
                            <template #button v-if="formEditable">
                                <van-uploader :after-read="didFinishPickingFiles">
                                    <van-button size="small" icon="plus" type="primary">上传附件</van-button>
                                </van-uploader>
                            </template>
                        </van-field>

                        <div v-for="(fileitem, index) in mFromdata.fjProveFile" :key="fileitem.id"
                            style="margin-left:20px">
                            <div readonly class="font14 fileLink" style="color:#0F85CF">
                                <a target="_blank" @click="openFileUrlfun(fileitem.anonymousFilePath)">{{
                                    fileitem.fileName
                                    }}</a>
                            </div>
                            <van-icon v-if="formEditable" name="close" color="#ea0023" size="20"
                                @click="deleteFile(index)"></van-icon>
                        </div>
                    </div>


                </div>


                <!-- 流转下一步 -->
                <div v-if="formEditable" class="footer">
                    <van-button block type="info" native-type="submit"
                        style="display: inline-block; width: 100%; border: 0px solid #60a9ec">确定</van-button>
                </div>
            </van-form>

        </div>

    </div>
</template>


<script>

import { mapGetters } from "vuex";
import { Notify, Toast } from "vant";
import moment from 'moment'

import { openFileUrl } from "@/store/openFile";
import util from "@/assets/js/public";
import jTool from "../../assets/js/jHelper";
import {
    getDictList,
    uploadFileCommon
} from "@/api/dictapi";

import { Append_lcb_KEY } from "../../assets/js/dict_process_helper";


export default {
    data() {
        return {

            params: this.$route.query,
            mFromdata: {},

            currentContractArrangePayTime: new Date(),
            showContractArrangePayTimePopupView: false,

            currentPlanEndDate: new Date(),
            showPlanEndDatePopupView:false,

            milestoneNodeShowPopop:false,
            milestoneNodeColumns:[],
        };
    },

    computed: {

        ...mapGetters(["user"]),
        ...mapGetters(["userinfo"]),

        formEditable() {
            return this.params.location === 'dict.start' || this.params.isDrawup == '1';
        },
    },

    //生命周期--创建完成
    created() {

        
    },

    //生命周期--进入
    activated() {

        // 每次进来重置数据
        this.params = this.$route.query;
        let formData = this.$route.query.formData;
        this.mFromdata = formData;

        this.$forceUpdate();
    },

    components: {

        
        

    },

    //生命周期--挂载完成
    mounted() { },

    //方法调用
    methods: {

        failedMethod(data) {

            console.log('submit fail:', data);
            const errorArr = data.errors;
            const errorObj = errorArr[0];
            const errorMessage = errorObj.message;
            Toast({ type: 'text', message: errorMessage, duration: 1000 });
        },

        openFileUrlfun(value) {
            this.$router.push({
                name: "fileview",
                query: {
                    openFileUrl: openFileUrl(value),
                },
            });
        },



        /// 获取数据
        /// 里程碑节点 下拉框数据
        requestMilestoneNodeInfo() {
            Toast.loading({ message: "加载中", forbidClick: false });
            getDictList('milestoneNode', { userName: this.user.userName }).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {
                    this.milestoneNodeColumns = result.data.data;
                    this.milestoneNodeShowPopop = true;
                }
            });
        },


        /// 年月日 时间格式
        formatter(type, val) {
            if (type === 'year') {
                return `${val}年`;
            }
            else if (type === 'month') {
                return `${val}月`;
            }
            else if (type === 'day') {
                return `${val}日`;
            }

            return val;
        },

        /// 本地文件选中后的回调
        didFinishPickingFiles(file) {

            let fileData = new FormData();
            fileData.append("pmInsType", this.pmInsType);
            fileData.append("pmInsTypePart", "1");
            fileData.append("files", file.file);

            let params = new Map();
            params.pmInsType = this.pmInsType;
            params.pmInsTypePart = '1';
            params.userName = this.user.userName;
            uploadFileCommon(fileData, params).then((res) => {
                if (!res.data) {
                    Notify(res.message);
                    return;
                }
                if (res.data.data) {
                    if (this.mFromdata.fjProveFile === null ||
                        this.mFromdata.fjProveFile === undefined) {
                        this.mFromdata.fjProveFile = [];
                    }

                    this.mFromdata.fjProveFile.push(res.data.data.sysFiles[0]);
                    this.$forceUpdate(); 
                }
            });
        },

        deleteFile(index) {
            Dialog.confirm({ title: "提示", message: "是否删除此附件？" })
                .then(() => {
                    this.mFromdata.reportFile.splice(index, 1);
                })
                .catch(() => { });
        },

        /// 合同约定交付时间 选中
        contractArrangePayTimeOnComfirm(value) {

            this.showContractArrangePayTimePopupView = false;

            let contractArrangePayTime = moment(value).format('YYYY-MM-DD');
            this.currentContractArrangePayTime = contractArrangePayTime;
            this.mFromdata.contractArrangePayTime = contractArrangePayTime;
        },

        // 里程碑计划完成时间 选中
        planEndDateOnComfirm(value) {

            this.showPlanEndDatePopupView = false;

            let planEndDate = moment(value).format('YYYY-MM-DD');
            this.currentPlanEndDate = planEndDate;
            this.mFromdata.planEndDate = planEndDate;

            if (!this.compareTime()) {
                Toast({ type: 'text', message: '里程碑计划完成时间要小于合同约定交付时间', duration: 1000 });
            }
        },

        // 时间对比、日期对比
        // "里程碑计划完成时间"对比"合同约定交付时间"，如果“合同约定交付时间”有值，则前者要要早于后者；如果无值，则不做对比
        compareTime() {

            if (jTool.stringIsEmpty(this.mFromdata.contractArrangePayTime)) {
                return true;
            }

            // 里程碑计划完成时间
            let planEndDate = new Date(this.mFromdata.planEndDate);
            let contractArrangePayTime = new Date(this.mFromdata.contractArrangePayTime);
            if (contractArrangePayTime - planEndDate >= 0) {
                return true;
            }
            
            return false;
        },
        

        // 里程碑节点 点击事件  首次点击做网络请求
        milestoneNodeClick () {
            
            if (this.milestoneNodeColumns.length === 0) {
                this.requestMilestoneNodeInfo();
            }
            else
            {
                this.milestoneNodeShowPopop = true;
            }
        },

        // 里程碑节点 选中
        milestoneNodeClickConfirm (value) {

            this.milestoneNodeShowPopop = false;
            this.mFromdata.milestoneNode = value.value;
        },


        sureButtonClick() {

            if (!this.compareTime()) {
                Toast({ type: 'text', message: '里程碑计划完成时间要小于合同约定交付时间', duration: 1000 });
                return;
            }

            localStorage.setItem(Append_lcb_KEY, JSON.stringify(this.mFromdata));
            this.$router.back();
        },

    },
};
</script>

<style scoped>
/* @import url();*/
</style>